package com.vivien.example.springbootdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vivien.example.springbootdemo.mapper.EcordersMapper;
import com.vivien.example.springbootdemo.mapper.EcpriceinfoMapper;
import com.vivien.example.springbootdemo.mapper.EcproductinfoMapper;
import com.vivien.example.springbootdemo.pojo.Ecorders;
import com.vivien.example.springbootdemo.pojo.Ecpriceinfo;
import com.vivien.example.springbootdemo.pojo.Ecproductinfo;
import com.vivien.example.springbootdemo.service.EcordersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EcordersServiceImpl extends ServiceImpl<EcordersMapper, Ecorders>
        implements EcordersService {
    @Autowired
    private EcordersMapper orderMapper;
    @Autowired
    private EcproductinfoMapper productInfoMapper;
    @Autowired
    private EcpriceinfoMapper priceInfoMapper;

    @Override
    public Map<String, Double> getCategoryPriceSum(Integer userId) {
        // 获取用户的订单
        List<Ecorders> orders = orderMapper.selectList(new LambdaQueryWrapper<Ecorders>().eq(Ecorders::getUserId, userId));
        System.out.println(orders);
        // 获取产品信息
        List<Ecproductinfo> productInfos = productInfoMapper.selectBatchIds(orders.stream().map(Ecorders::getProductId).collect(Collectors.toList()));

        // 获取价格信息
        List<Ecpriceinfo> priceInfos = priceInfoMapper.selectBatchIds(orders.stream().map(Ecorders::getProductId).collect(Collectors.toList()));

        // 计算总价
        Map<String, Double> categoryPriceMap = new HashMap<>();
        for (Ecorders order : orders) {
            Ecproductinfo productInfo = productInfos.stream().filter(p -> p.getProductId().equals(order.getProductId())).findFirst().orElse(null);
            Ecpriceinfo priceInfo = priceInfos.stream().filter(p -> p.getProductId().equals(order.getProductId())).findFirst().orElse(null);
            if (productInfo != null && priceInfo != null) {
                categoryPriceMap.put(productInfo.getProductCategory(),
                        categoryPriceMap.getOrDefault(productInfo.getProductCategory(), 0.0) + priceInfo.getPrice());
            }
        }

        // 计算百分比
        double total = categoryPriceMap.values().stream().mapToDouble(Double::doubleValue).sum();
        Map<String, Double> result = new HashMap<>();
        for (Map.Entry<String, Double> entry : categoryPriceMap.entrySet()) {
            result.put(entry.getKey(), (entry.getValue() / total) * 100);
        }
        return result;
    }

    @Override
    public Map<String, List<Double>> getUserPriceChangeLast5Years(Integer userId) {
        // 定义查询的年份范围
        List<Integer> years = Arrays.asList(2019, 2020, 2021, 2022, 2023, 2024);

        // 从订单表中筛选出指定用户在过去五年的订单
        List<Ecorders> orders = orderMapper.selectList(
                new LambdaQueryWrapper<Ecorders>()
                        .eq(Ecorders::getUserId, userId)
                        .apply("DATE(order_time) BETWEEN {0} AND {1}",
                                LocalDate.of(2019, 1, 1),
                                LocalDate.of(2024, 12, 31))
        );

        // 提取订单中的产品ID
        Set<Integer> productIds = orders.stream()
                .map(Ecorders::getProductId)
                .collect(Collectors.toSet());

        // 从产品信息表中获取产品类别
        Map<Integer, String> productCategoryMap = productInfoMapper.selectBatchIds(new ArrayList<>(productIds))
                .stream()
                .collect(Collectors.toMap(Ecproductinfo::getProductId, Ecproductinfo::getProductCategory));

        // 从价格更新表中获取过去五年内每年的产品价格
        List<Ecpriceinfo> priceInfos = priceInfoMapper.selectList(
                new LambdaQueryWrapper<Ecpriceinfo>()
                        .in(Ecpriceinfo::getProductId, productIds)
                        .apply("DATE(time_stamp) BETWEEN {0} AND {1}",
                                LocalDate.of(2019, 1, 1),
                                LocalDate.of(2024, 12, 31))
        );

        // 初始化结果Map，键为产品类别，值为按年份存储的价格列表
        Map<String, List<Double>> result = new HashMap<>();
        for (String category : productCategoryMap.values()) {
            result.put(category, new ArrayList<>(Collections.nCopies(years.size(), 0.0)));
        }

        // 遍历价格信息，更新结果Map
        for (Ecpriceinfo priceInfo : priceInfos) {
            String category = productCategoryMap.get(priceInfo.getProductId());
            if (category != null) {
                int yearIndex = years.indexOf(Year.from(LocalDate.parse(priceInfo.getTimeStamp())).getValue());
                if (yearIndex != -1) {
                    List<Double> prices = result.get(category);
                    prices.set(yearIndex, prices.get(yearIndex) + priceInfo.getPrice());
                }
            }
        }

        return result;
    }
}
